package cn.vshare.service.impl;

import cn.vshare.dao.VideoDao;
import cn.vshare.entity.Kind;
import cn.vshare.entity.User;
import cn.vshare.entity.Video;
import cn.vshare.service.VideoService;
import cn.vshare.util.DateUtil;
import cn.vshare.util.VideoUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Service
public class VideoServiceImpl implements VideoService {
    @Autowired
    private VideoDao videoDao;
    @Autowired
    private VideoUtil videoUtil;

    @Override
    public void addVideo(Video video) {
        videoDao.insertVideo(video);
    }

    /**
     * 根据用户id 和种类id 查询视频
     * @param userId
     * @param kindId
     * @return
     */

    @Override
    public Page<Video> getVideosByUserIdKinId(String userId, String kindId, int pageSize, int pageNum) {
        int total=videoDao.getVideosCountByUserIdKinId(userId,kindId);
        Page<Video> page=PageHelper.startPage(pageNum,pageSize);
        List<Video> list=videoDao.getVideosByUserIdKinId(userId,kindId);
        page.setTotal(total);
        return page;
    }




    @Override
    public Map createVideo(String videoUtilId, Video video, MultipartFile file, HttpServletRequest request) {
        Map map = new HashMap();
        String id = UUID.randomUUID().toString();
        User user = (User) request.getSession().getAttribute("USER");
        video.setId(id);
        video.setUser(user);
        video.setPageview(1L);
        video.setUploadDate(DateUtil.getCurrDate());
        String name = file.getOriginalFilename();

        String contextPath = request.getContextPath();
        System.out.println(contextPath);

        String videoTempPath = "E:\\javaworkspace\\VShare\\src\\main\\webapp\\file\\video\\aaaaatemp";
        String videoPath = "E:\\javaworkspace\\VShare\\src\\main\\webapp\\file\\video";
        String imagePath = "E:\\javaworkspace\\VShare\\src\\main\\webapp\\file\\image";
        String videoTempPathWithName = videoTempPath + "\\" + name;

        if (videoUtil.checkAllowFiles(name)) {
            File upfile = new File(name);
            try {
                file.transferTo(upfile);
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (videoUtil.checkFlv(name)){
                String str=UUID.randomUUID().toString().replace("-","");
                String videoName=str+".flv";
                String pivName=str+".jpg";
                try {
                    videoUtil.processFlv(videoUtilId,VideoUtil.ffmpegPath,videoTempPathWithName,videoPath+"\\"+videoName);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                video.setName(videoName);
                video.setLocation("/file/video/"+videoName);
                videoUtil.getPic(VideoUtil.ffmpegPath,videoTempPathWithName,imagePath+"\\"+pivName);
                video.setPic("/file/image/"+pivName);

                map.put("video",video);

                return map;
            } else {
                String str=UUID.randomUUID().toString().replace("-","");
                String picName=str+".jpg";
                video.setName(name);
                video.setLocation("/file/video/"+name);
                videoUtil.getPic(VideoUtil.ffmpegPath,videoTempPathWithName,imagePath+"\\"+picName);
                video.setPic("/file/image/"+picName);
            }
        }
        map.put("video",video);
        map.put("videoUtil",this.videoUtil);
        return map;
    }

    @Override
    public Page<Video> queryVideoByKindId(Map<String,Object> cond) {

        Page<Video> page=new Page<Video>();
        //设置总记录数
        int count=videoDao.queryVideoByKindIdCount(cond);
        //获取页大小并赋值给page
        int pageSize=Integer.parseInt(String.valueOf(cond.get("pageSize")));
        //获取当前页码
        int curPageNum=Integer.parseInt(String.valueOf(cond.get("pageNo")));
        //计算总页数
        page.setTotal(count);
        page.setPageSize(pageSize);
        int totalPages=(count/ pageSize + (count % pageSize == 0 ? 0 : 1));
        page.setPageNum(totalPages);
        page=PageHelper.startPage(curPageNum,pageSize);
        List<Video> videoList=videoDao.queryVideoByKindId(cond);
        return page;
    }

    @Override
    public Page<Video> getLikeVideos(Map<String, Object> cond) {
        Page<Video> page = new Page<Video>();
        //记录总数
        int cound=videoDao.AllCount(cond);
        page.setTotal(cound);
        //获取页面大小并且赋给page
        int pageSize= (int) cond.get("pageSize");
        page.setPageSize(pageSize);
        //获取当前页码
        int currPageNum= (int) cond.get("pageNum");

        //计算总页数
        int total= (int) (page.getTotal()/pageSize+(page.getTotal()%pageSize == 0 ? 0 :1));
        System.out.println("total"+total);
        page.setPageNum(total);
        String str= (String) cond.get("search");
        page=PageHelper.startPage(currPageNum,pageSize);//开始分页
        List<Video> list=videoDao.getLikeVideos(str);
        return page;
    }


    @Override
    public Page<Video> getVideoByUpTimeAndName(Map<String, Object> cond) {
        Page<Video> page = new Page<Video>();
        //设置总记录数
        int count = videoDao.AllCount(cond);
        page.setTotal(count);
        //获取页大小并赋值给page
        int pageSize = Integer.parseInt(String.valueOf(cond.get("pageSize")));
        page.setPageSize(pageSize);
        //获取当前页码
        int curPageNum = Integer.parseInt(String.valueOf(cond.get("pageNum")));
        //计算总页数
        int aa = (int) (page.getTotal() / pageSize + (page.getTotal() % pageSize == 0 ? 0 : 1));
        page.setPageNum(aa);
        page = PageHelper.startPage(curPageNum, pageSize);//开启分页
        List<Video> videoList = videoDao.getVideoByUpTimeAndName(cond);
        return page;

    }

    @Override
    public Page<Video> queryVideoByUserId(int pageNum, int pageSize, String userId) {
        Page page= PageHelper.startPage(pageNum,pageSize);
        List<Video> list=videoDao.queryVideoByUserId(userId);
        int total=videoDao.queryAllVideoByUserId(userId);
        page.setTotal(total);
        return page;
    }

    @Override
    public int countVideoTypeByKind(Kind kind) {
        return videoDao.countVideoTypeByKind(kind);
    }
    @Override
    public Video queryVideoById(String id) {
        return videoDao.queryVideoById(id);
    }

    /**
     * 用来统计播放量的方法
     * @param id
     */
    @Override
    public void updatePageview(String id) {
        Video video= videoDao.queryVideoById(id);
        Long oldPageview=video.getPageview();
        if(oldPageview==null||oldPageview==0){
            video.setPageview(1L);
        }else{
            oldPageview+=1;
            video.setPageview(oldPageview);
        }
        videoDao.updatePageview(video);
    }

    @Override
    public int countVideoByAge(Map<String, Object> map) {
        return videoDao.countVideoByAge(map);
    }

    @Override
    public Video getVideoById(String id) {
        return videoDao.getVideoById(id);
    }



    @Override
    public void updateVideoById(String id,String status) {
        Map<String,Object> map = new HashMap<String, Object>();
        map.put("id",id);
        map.put("status",status);
        videoDao.updateVideoById(map);
    }

    @Override
    public void updateHYById(String id) {
        Map<String,Object> map = new HashMap<String, Object>();
        map.put("id",id);
        videoDao.updateVideoById(map);
    }

    @Override
    public int countViewTimesByKind(Kind kind) {
        Integer num=videoDao.countViewTimesByKind(kind);
        if (num==null){
            //如果查询结果为空,则返回值为0
            num=0;
        }
        return num;
    }

    @Override
    public int updateVideo(Video video) {
        return videoDao.updateVideo(video);
    }


    @Override
    public PageInfo<Video> getVideosByUserIdKindIdTitle(Video video, int pageSize, int pageNum) {
        Page page= PageHelper.startPage(pageNum,pageSize);
        List<Video> list=videoDao.getVideosByUserIdKindIdTitle(video);
        int total=videoDao.getVideosCountByUserIdKindIdTitle(video);
        page.setTotal(total);
        return new PageInfo<Video>(page);
    }
}
